package model

import (
	"gorm.io/gorm"
	"seckill-srv/basic/config"
)

type Goods struct {
	gorm.Model
	UserId      int     `json:"user_id" gorm:"type:int;comment:'用户id'"`
	GoodsTitle  string  `json:"goods_title" gorm:"type:varchar(50);comment:'商品名称'"`
	GoodsDesc   string  `json:"goods_desc" gorm:"type:varchar(200);comment:'商品描述'"`
	GoodsPrice  float32 `json:"goods_price" gorm:"type:decimal(10,2);comment:'商品价格'"`
	Stock       int     `json:"stock" gorm:"type:int;comment:'商品库存'"`
	GoodsImg    string  `json:"goods_img" gorm:"type:varchar(200);comment:'商品图片'"`
	GoodsStatus int     `json:"goods_status" gorm:"type:int;comment:'商品状态 1-上架 2-下架'"`
}

func (g *Goods) TableName() string {
	return "goods"
}

// 添加商品
func (g *Goods) AddGoods() error {
	return config.DB.Create(&g).Error
}

// 根据id查询商品
func (g *Goods) GetGoodsById(goodsId int) error {
	return config.DB.Model(&Goods{}).Where("id = ?", goodsId).Limit(1).Find(&g).Error
}

// 扣减库存
func (g *Goods) UpdateGoodsStock(tx *gorm.DB, goodsId int, stock int) error {
	return config.DB.Model(&Goods{}).Where("id = ?", goodsId).Update("stock", stock).Error
}
